# Set version
$VERSION = Get-Date -Format "yyyyMMdd_HHmmss"

# Run tests
Write-Host "Running unit tests..."
npm test
if ($LASTEXITCODE -ne 0) {
    Write-Host "Tests failed, build aborted"
    exit 1
}

# Build multi-container system
Write-Host "Building multi-container system..."
docker-compose -f docker-compose.prod.yml build

# Create release directory
New-Item -ItemType Directory -Force -Path "release"

# Save all images as tar files
Write-Host "Saving images as tar files..."

# Check if images exist before saving
$imagesToSave = @(
    @{Name="postgres:15-alpine"; File="postgres_${VERSION}.tar"},
    @{Name="experiment-backend:latest"; File="backend_${VERSION}.tar"},
    @{Name="experiment-frontend:latest"; File="frontend_${VERSION}.tar"}
)

foreach ($image in $imagesToSave) {
    docker image inspect $image.Name 2>$null
    if ($LASTEXITCODE -eq 0) {
        Write-Host "Saving $($image.Name)..."
        docker save $image.Name -o "release/$($image.File)"
        if ($LASTEXITCODE -eq 0) {
            Write-Host "Successfully saved $($image.File)"
        } else {
            Write-Host "Failed to save $($image.File)"
        }
    } else {
        Write-Host "Warning: Image $($image.Name) not found, skipping..."
    }
}

Write-Host "Multi-container build completed!"
Write-Host "Images saved to:"
Write-Host "- release/postgres_${VERSION}.tar"
Write-Host "- release/backend_${VERSION}.tar"
Write-Host "- release/frontend_${VERSION}.tar"
Write-Host ""
Write-Host "Usage:"
Write-Host "1. Copy all tar files to target server"
Write-Host "2. Run: docker load -i postgres_${VERSION}.tar"
Write-Host "3. Run: docker load -i backend_${VERSION}.tar"
Write-Host "4. Run: docker load -i frontend_${VERSION}.tar"
Write-Host "5. Run: docker-compose -f docker-compose.prod.yml up -d" 
 
